package com.youdoneed.user.CoolfaceNotice;

import com.querydsl.sql.SQLQueryFactory;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.user.model.CoolfaceNotice;
import com.youdoneed.user.query.QCoolfaceNotice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author lid
 * @since 2017-11-14
 **/
@Service
@Transactional(rollbackFor = Throwable.class)
public class CoolfaceNoticeServiceImpl implements CoolfaceNoticeService{

    private static final Logger logger = LoggerFactory.getLogger(CoolfaceNoticeServiceImpl.class);

    @Autowired
    private SQLQueryFactory queryFactory;

    private QCoolfaceNotice qCoolfaceNotice = QCoolfaceNotice.CoolfaceNotice;

    /**
     * 保存coolface通知
     * @param coolfaceNotice
     * @author lid
     * @date 2017.11.14
     */
    @Override
    public void saveCoolfaceNotice(CoolfaceNotice coolfaceNotice) {
        if(null == coolfaceNotice){
            throw new AppException("通知为空");
        }

        if(!StringUtils.hasText(coolfaceNotice.getNoticeId())){
            coolfaceNotice.setNoticeId(GlobalIdWorker.nextString());
        }

        try {
            queryFactory.insert(qCoolfaceNotice)
                    .populate(coolfaceNotice)
                    .execute();
        }catch (Exception e){
            throw new AppException("保存coolface通知失败");
        }
    }

    /**
     * 获取coolface通知
     * @param userId
     * @author lid
     * @date 2017.11.14
     */
    @Override
    public List<CoolfaceNotice> getCoolfaceNoticeByUserId(String userId) {
        if(!StringUtils.hasText(userId)){
            throw new AppException("userId为空");
        }

        try {
            return queryFactory.selectFrom(qCoolfaceNotice)
                    .where(qCoolfaceNotice.userId.eq(userId))
                    .where(qCoolfaceNotice.hasRead.eq(0))
                    .orderBy(qCoolfaceNotice.createDate.desc())
                    .fetch();

        }catch (Exception e){
            throw new AppException("");
        }
    }

    @Override
    public long readCoolfaceNotice(String noticeId) {
        if(!StringUtils.hasText(noticeId)){
            throw new AppException("noticeId为空");
        }

        try {
            return queryFactory.update(qCoolfaceNotice)
                               .set(qCoolfaceNotice.hasRead, 1)
                               .where(qCoolfaceNotice.noticeId.eq(noticeId))
                               .execute();
        }catch (Exception e){
            throw new AppException("");
        }
    }
}
